package com.lvandroid.transport;

import android.text.TextUtils;

import com.lvandroid.transport.download.HttpsDownLoader;
import com.lvandroid.transport.download.IDownLoad;
import com.lvandroid.transport.upload.HttpsUpLoader;
import com.lvandroid.transport.upload.IUpLoad;

import java.util.HashMap;
import java.util.Map;

/**
 * 上传下载管工具
 */
public class DownloadManager {

    private static DownloadManager sINSTANCE;
    private static byte[] sOBJ = new byte[0];

    private Map<String, IDownLoad> mDownLoaders = new HashMap<>();
    private Map<String, IUpLoad> mUpLoaders = new HashMap<>();

    public static DownloadManager getInstance() {
        if(null == sINSTANCE) {
            synchronized (sOBJ) {
                if (null == sINSTANCE) {
                    sINSTANCE = new DownloadManager();
                }
            }
        }

        return sINSTANCE;
    }

    private DownloadManager() {
        initDownLoaders();
        initUpLoaders();
    }

    /**
     * 初始化下载器，目前只创建http/https协议的下载器，后续可以扩展
     */
    private void initDownLoaders() {
        mDownLoaders.put(IDownLoad.DOWNLOADER_HTTPS, new HttpsDownLoader());
    }

    /**
     * 初始化上传器，目前只创建http/https协议的上传器，后续可以扩展
     */
    private void initUpLoaders() {
        mUpLoaders.put(IUpLoad.UPLOADER_HTTPS, new HttpsUpLoader());
    }

    /**
     * 获取下载器
     * @param downLoaderName
     * @return
     */
    public IDownLoad getDownLoader(String downLoaderName) {
        if(TextUtils.isEmpty(downLoaderName)) {
            throw new IllegalArgumentException("Downloader name can not be null!");
        }
        IDownLoad downLoad = mDownLoaders.get(downLoaderName);
        if(null == downLoad) {
            throw new UnsupportedOperationException("Can not find downloader for type : " + downLoaderName);
        }

        return downLoad;
    }

    /**
     * 获取上传器
     * @param upLoaderName
     * @return
     */
    public IUpLoad getUpLoader(String upLoaderName) {
        if(TextUtils.isEmpty(upLoaderName)) {
            throw new IllegalArgumentException("Uploader name can not be null!");
        }
        IUpLoad upLoad = mUpLoaders.get(upLoaderName);
        if(null == upLoad) {
            throw new UnsupportedOperationException("Can not find uploader for type : " + upLoaderName);
        }

        return upLoad;
    }

}
